package cn.tianyigps.tianyigpsapiv2.oauth2.service;

import cn.tianyigps.tianyigpsapiv2.oauth2.entity.FortUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("mongoUserDetailsService")
public class MongoUserDetailsService implements UserDetailsService {

	private final String USER_CONLLECTION = "user";
	@Autowired
	private MongoTemplate mongoTemplate;
	
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		FortUserDetails user = mongoTemplate.findOne(new Query(Criteria.where("username").is(username)), FortUserDetails.class, USER_CONLLECTION);
//		if(user == null) {
//			throw new RuntimeException("查询用户信息时出现异常");
//		}
////		String roleType = user.getRoleType();
////		if(roleType == null || "".equals(roleType)) {
////			throw new RuntimeException("用户未分配权限");
////		}
		user.setAccountNonExpired(true);
		user.setAccountNonLocked(true);
		user.setCredentialsNonExpired(true);
		user.setEnabled(true);
//		user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
		List<GrantedAuthority> roleList = new ArrayList<>();
		GrantedAuthority ga = new SimpleGrantedAuthority("ROLE_USER");
		roleList.add(ga);
		user.setAuthorities(roleList);
		return user;
	}

}